package com.ruibang.glass.quality.component.job;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ruibang.glass.quality.constant.Constants;
import com.ruibang.glass.quality.domain.req.BcStationHqDetailReq;
import com.ruibang.glass.quality.domain.req.DiscardDefectReq;
import com.ruibang.glass.quality.entity.BandDefectData;
import com.ruibang.glass.quality.entity.BcStationHqDetail;
import com.ruibang.glass.quality.entity.Defect;
import com.ruibang.glass.quality.service.BandDefectDataService;
import com.ruibang.glass.quality.service.DefectGroupService;
import com.ruibang.glass.quality.service.GlassBindTestService;
import com.ruibang.glass.quality.service.impl.TotalEquDataServiceImpl;
import com.teaming.cloud.framework2.elastic.job3.annotation.ElasticJobScheduler;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.elasticjob.api.ShardingContext;
import org.apache.shardingsphere.elasticjob.simple.job.SimpleJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/***
 * 归档缺陷曲线数据支撑统计
 */
@Slf4j
@ElasticJobScheduler(cron = "9 40 0/1 * * ?", name = "DiscardArchiveDefectDataTask", shardingItemParameters = "0=0", jobParameters = "parameter")
//@ElasticJobScheduler(cron = "9 * * * * ?", name = "DiscardArchiveDefectDataTask", shardingItemParameters = "0=0", jobParameters = "parameter")
@Component
public class DiscardArchiveDefectDataTask implements SimpleJob {

    @Autowired
    private TotalEquDataServiceImpl totalEquDataService;

    @Autowired
    private DefectGroupService defectGroupService;

    @Autowired
    private BandDefectDataService bandDefectDataService;

    @Autowired
    private GlassBindTestService glassBindTestService;

    /**
     * 归档缺陷待返投数据支撑
     */
    @Override
    public void execute(ShardingContext shardingContext) {
        LocalDate now = LocalDate.now();
        String startDate = now.minusDays(15).format(DateTimeFormatter.ISO_LOCAL_DATE);
        String endDate = now.format(DateTimeFormatter.ISO_LOCAL_DATE);

        //查询时间段所有冷端玻璃ID，获取缺陷数据
        BcStationHqDetailReq bcStationHqDetailReq = new BcStationHqDetailReq();
        bcStationHqDetailReq.setStartDate(startDate);
        bcStationHqDetailReq.setEndDate(endDate);
        Collection<BcStationHqDetail> transects = glassBindTestService.getTransects(bcStationHqDetailReq);

        Map<String, LocalDateTime> glassMap = new HashMap<>();

        List<String> glassIds = new ArrayList<>();
        for (BcStationHqDetail transect : transects) {
            //横切时间
            Instant instant = Instant.ofEpochMilli(Long.parseLong(transect.getStationStartTime()));
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime stationStartTime = LocalDateTime.ofInstant(instant, zoneId);
            //冷端玻璃id
            if (CollectionUtils.isNotEmpty(transect.getGlassIds())) {
                //glassId mapping stationStartTime
                for (String glassId : transect.getGlassIds()) {
                    String gId = glassId.substring(6);
                    glassMap.put(gId, stationStartTime);
                    glassIds.add(gId);
                }
            }
        }

        if (CollectionUtils.isNotEmpty(glassIds)) {
            //获取缺陷配置
            DiscardDefectReq defectReq = new DiscardDefectReq();
            defectReq.setStartDate(startDate);
            defectReq.setEndDate(endDate);
            defectReq.setCheckMachineCode("CM1");
            //检查机类型0:冷端，1:热端
            defectReq.setCheckMachineType(Constants.ZERO_STR);
            //检查机类型0:半成品，1:成品
            defectReq.setIsFinished(Constants.ONE_STR);
            log.error("bandDefectData defectReq:{}", defectReq);
            List<Defect> defects = defectGroupService.getByCheckMachine(defectReq.getCheckMachineCode(), defectReq.getCheckMachineType());

            if (CollectionUtils.isNotEmpty(defects)) {
                StringBuilder sql = new StringBuilder();
                AtomicInteger i = new AtomicInteger(1);

                Map<String, List<Defect>> defectMap = defects.stream().collect(Collectors.groupingBy(e -> e.getDefectName() + "_" + e.getDefectCode()));
                String isFinished = defectReq.getIsFinished();
                String checkMachineType = defectReq.getCheckMachineType();
                defectMap.forEach((k, v) -> {
                    String[] split = k.split("_");
                    String defectCode = split[1];
                    String defectName = split[0];
                    if (i.get() > 1) {
                        sql.append(" union ");
                    }
                    sql.append("SELECT CustomerPanelId,DefectName,MaterialCenterDW,MaterialCenterCW,TiltedSize,TiltedDiv FROM total_equ_data where ");
                    sql.append("is_finished = ").append(isFinished);
                    sql.append(" AND MachineId ='Inspect' ");
                    sql.append("AND DefectName = '").append(defectCode).append("' AND(");
                    for (int j = 0; j < v.size(); j++) {
                        Defect value = v.get(j);
                        sql.append("(");
                        double minSize = value.getMinSize() / 1000f;
                        double maxSize = value.getMaxSize() / 1000f;
                        sql.append("TiltedSize >= ").append(minSize);
                        sql.append(" AND TiltedSize <= ").append(maxSize);

                        if (Constants.ZERO_STR.equals(checkMachineType)) {
                            sql.append(" AND TiltedDiv >= ").append(value.getMinLayerDepth());
                            sql.append(" AND TiltedDiv <= ").append(value.getMaxLayerDepth());
                        }

                        if (j == v.size() - 1) {
                            sql.append(")");
                        } else {
                            sql.append(") or ");
                        }
                    }
                    sql.append(") ");
//                sql.append(") AND DATE_FORMAT(StationStartTime,'%Y-%m-%d') between ").append("'").append(startDate).append("'").append(" AND ");
//                sql.append("'").append(endDate).append("'");
                    if (CollectionUtils.isNotEmpty(glassIds)) {
                        sql.append("and CustomerPanelId in (");
                        for (int j = 0; j < glassIds.size(); j++) {
                            sql.append("'");
                            sql.append(glassIds.get(j));
                            if (j == glassIds.size() - 1) {
                                sql.append("'");
                            } else {
                                sql.append("',");
                            }
                        }
                        sql.append(")");
                    }
                    i.getAndIncrement();
                });

                log.error("冷端缺陷待返投数据支撑 执行查询语句{}:{}", defectReq.getCheckMachineType().equals(Constants.ZERO_STR) ? "冷端" : "热端", sql);

                List<BandDefectData> bandDefectDataList = totalEquDataService.queryBandDefectData(sql.toString());

                if (CollectionUtils.isNotEmpty(bandDefectDataList)) {
                    //设置横切时间
                    for (BandDefectData bandDefectData : bandDefectDataList) {
                        LocalDateTime stationStartTime = glassMap.get(bandDefectData.getCustomerPanelId());
                        if (stationStartTime != null) {
                            bandDefectData.setStationStartTime(stationStartTime);
                        }
                    }
                    bandDefectDataList = bandDefectDataList.stream().filter(e -> e.getStationStartTime() != null).collect(Collectors.toList());
                    //保存
                    bandDefectDataService.deleteByDate(defectReq);
                    bandDefectDataService.saveBatch(bandDefectDataList);
                }
            }
        }
    }
}
